package com.pi.smart.wxmini.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.pi.base.dto.result.AppResult;
import com.pi.common.http.annotation.InterceptorIgnore;
import com.pi.http.base.controller.BaseController;
import com.pi.uc.dao.entity.UcUserWxEntity;
import com.pi.uc.model.user.UserExtendPostForm;
import com.pi.uc.model.userlogin.UserLoginPostForm;
import com.pi.uc.model.wx.mini.WxFullUserInfo;
import com.pi.uc.service.UcUserService;
import com.pi.uc.service.UcUserWxService;
import com.pi.uc.vo.UserExtendInfoVo;
import com.pi.uc.vo.UserWechatBindVo;

@RequestMapping("/user")
@RestController
public class SmartWXController extends BaseController{
  private static final Logger logger = LoggerFactory.getLogger(SmartWXController.class);
  @Autowired
  private UcUserService userService;
  @Autowired
  private UcUserWxService userWxService;
  
  @InterceptorIgnore(desc = "微信绑定登陆")
  @RequestMapping("/wechat/bind")
  public AppResult weChatBind(UserLoginPostForm user) throws Exception{
    logger.debug("[微信绑定登陆] 来源:{}, 校验码：{}", user.toString());
    UserWechatBindVo vo = userService.bindWeChatVo(user);
    return AppResult.newSuccessResult(vo);
  }
  
  @InterceptorIgnore(desc = "微信绑定登陆")
  @GetMapping("/token")
  public AppResult getToken() throws Exception{
    String token = userService.getTokenByUserId(getLoginUserId());
    return AppResult.newSuccessResult(token);
  }

  @PostMapping("/info/add")
  public AppResult addUserInfo(@RequestBody WxFullUserInfo userFullInfo){
    logger.debug("[修改用户信息] 内容为：{}", JSON.toJSONString(userFullInfo));
    userService.addUserInfoWithExtendByWeChat(userFullInfo, getLoginUserId());
    return AppResult.OK;
  }
  
  @PostMapping("/info/update")
  public AppResult updateUserInfo(UserExtendPostForm user){
    logger.debug("[修改用户信息] 内容为：{}", JSON.toJSONString(user));
    user.setLoginUserId(getLoginUserId());
    userService.updateUserInfoWithExtend(user);
    return AppResult.OK;
  }
  
  @GetMapping("/info")
  public AppResult getUserInfo(){
    logger.debug("[获取用户信息] 当前用户为为：{}", getLoginUserId());
    UserExtendInfoVo entity = userService.queryUserFullInfo(getLoginUserId());
    return AppResult.newSuccessResult(entity);
  }
  
  @GetMapping("/openid")
  public AppResult openid(){
    logger.debug("[获取用户的openid] 当前用户为为：{}", getLoginUserId());
    UcUserWxEntity entity = userWxService.queryUserWxInfo(getLoginUserId());
    return AppResult.newSuccessResult(entity.getWxOpenid());
  }
}
